import React, { useState, useEffect } from "react";
import { Table, message, Button, Input, Modal, Form, Upload, Space, DatePicker, Spin } from "antd";
import { DeleteOutlined, PlusOutlined, UploadOutlined, EyeOutlined, EditOutlined } from '@ant-design/icons';

import { get, post } from "../../../components/axios";
import DocumentPreview from "../../../components/DocumentPreview";
import '../../cssmodule/word-preview-content.module.css'
import { DocumentUtils } from "../../../utils/documentUtils";
import dayjs from 'dayjs';


export default function ProjectMeetingNotes() {
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [currentFile, setCurrentFile] = useState(null);
  const [form] = Form.useForm();
  const [searchValue, setSearchValue] = useState('');
  const [editingId, setEditingId] = useState(null);
  const [cahierPreview, setCahierPreview] = useState(null);
  const getList = async () => {
    try {
      setLoading(true);
      const res = await get("PMrecord/getMeetingNotes");
      setList(res.data);
    } catch (error) {
      message.error('获取会议纪要失败');
    } finally {
      setLoading(false);
    }
  };
  //搜索
  const handleSearch = async (value) => {
    setLoading(true);
    console.log(value);
    console.log(searchValue);

    try {
      setLoading(true);
      const res = await get("PMrecord/getMeetingNotes", { keyword: value });
      setList(res.data || []);
    } catch (error) {
      message.error('获取会议纪要失败');
    } finally {
      setLoading(false);
    }
  };
  //删除会议纪要

  const handleDelete = async (record) => {
    Modal.confirm({
      title: '确认删除这条会议纪要吗？',
      onOk: async () => {
        try {
          await post('PMrecord/deleteAttachment', { _id: record._id });
          message.success('删除成功');
          getList();
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  const handleFinish = async (values) => {
    try {

      const formData = new FormData();
      

      // 会议时间拼接
      const meetingTime = values.startTime && values.endTime
        ? `${values.startTime.format('YYYY-MM-DD HH:mm')}--${values.endTime.format('YYYY-MM-DD HH:mm')}`
        : '';
      formData.append('MeetingTime', meetingTime);
      formData.append('MeetingName', values.MeetingName);
      formData.append('Participants', values.Participants);
      formData.append('cahier', values.cahier);
      formData.append('creator', values.creator || '默认创建人');
      formData.append('createTime', new Date().toLocaleString('zh-CN', { hour12: false }));

      // 处理文件上传
      if (values.file && values.file[0]) {
        if (values.file[0].originFileObj) {
          // 新上传的文件
          formData.append('file', values.file[0].originFileObj);
        } else if (values.file[0].url) {
          // 已有文件，后端可根据 url 或 name 识别，不需要重复上传
          formData.append('fileUrl', values.file[0].url);
          formData.append('fileName', values.file[0].name);
        }
        formData.append('type', '会议纪要');
      }
      if (values.cahier && values.cahier[0]) {
        if (values.cahier[0].originFileObj) {
          formData.append('cahierFile', values.cahier[0].originFileObj); // 这里必须是cahierFile
        } else if (values.cahier[0].url) {
          formData.append('cahierUrl', values.cahier[0].url);
          formData.append('cahierName', values.cahier[0].name);
        }
      }

      if (editingId) {
        formData.append('_id', editingId);
        console.log(formData, 81);

        await post('PMrecord/updateAttachment', formData);
        message.success('编辑成功');
      } else {
        // 新增
        console.log(formData, 89);

        await post('PMrecord/addAttachment', formData);
        message.success('添加成功');
      }

      setModalVisible(false);
      setEditingId(null); // 关键：重置编辑状态
      form.resetFields();
      getList();
    } catch (error) {
      message.error(editingId ? '编辑失败' : '添加失败');
      console.error(error);
    }
  };

  // 处理文件预览
  const handlePreview = (record, type) => {
    if (type === 1) {
      if (!record.cahierUrl || !record.cahierName) {
        message.warning('文件不存在');
        return;
      }

      setCurrentFile({
        url: record.cahierUrl,
        name: record.cahierName
      });

    } else {
      if (!record.url || !record.name) {
        message.warning('文件不存在');
        return;
      }

      setCurrentFile({
        url: record.url,
        name: record.name
      });
    }


    setPreviewVisible(true);
  };

  // 处理文件信息的回显
  const handleEdit = (record) => {
    console.log('handleEdit', record);
    setEditingId(record._id);
    form.setFieldsValue({
      startTime: dayjs(record.MeetingTime.split('--')[0]),
      endTime: dayjs(record.MeetingTime.split('--')[1]),
      MeetingName: record.MeetingName,
      Participants: record.Participants,
      cahier: record.cahierUrl && record.cahierName ? [{
        name: record.cahierName,
        url: record.cahierUrl
      }] : [],
      creator: record.creator,
      file: [
        {
          name: record.name,
          url: record.url
        }
      ]
    });


    setModalVisible(true);
  };




  const columns = [
    {
      title: 'ID',
      dataIndex: '_id',
      key: '_id',
      render: (text, record, index) => index + 1
    },
    {
      title: '会议时间',
      dataIndex: 'MeetingTime',
      key: 'MeetingTime'
    },
    {
      title: '会议主题',
      dataIndex: 'MeetingName',
      key: 'MeetingName'
    },
    {
      title: '参会人',
      dataIndex: 'Participants',
      key: 'Participants'
    },
    {
      title: '会议事项记录',
      dataIndex: 'cahier',
      key: 'cahier',
      render: (text, record) => {
        if (!record.cahierUrl || !record.cahierName) return '-';
        const isPreviewable = DocumentUtils.isPreviewable(record.cahierName);
        return (
          <Space>
            <span>{record.cahierName}</span>
            {isPreviewable && (
              <Button
                type="link"
                size="small"
                onClick={() => handlePreview(record, 1)}
              >
                查看
              </Button>
            )}
          </Space>
        );
      }
    },
    {
      title: '附件',
      dataIndex: 'url',
      key: 'url',
      render: (text, record) => {
        if (!record.url || !record.name) {
          return '-';
        }

        const isPreviewable = DocumentUtils.isPreviewable(record.name);

        return (
          <Space>
            <span>{record.name}</span>
            {isPreviewable && (
              <Button
                type="link"
                size="small"
                icon={<EyeOutlined />}


                onClick={() => handlePreview(record, 2)}
              >
                预览
              </Button>
            )}
          </Space>
        );
      }
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime'
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <div>
          <Button
            type="link"
            shape="circle"
            icon={<EditOutlined />}
            style={{ background: '#52c41a', borderColor: '#52c41a', color: '#fff' }}
            onClick={() => handleEdit(record)}
          >

          </Button>
          <Button
            type="primary"
            shape="circle"
            icon={<DeleteOutlined />}
            danger={false}
            style={{ background: 'red', borderColor: '#52c41a', color: '#fff' }}
            onClick={() => handleDelete(record)}
          />
        </div>
      )
    }
  ];

  useEffect(() => {
    getList();
  }, []);

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
        <Button type="primary" onClick={() => setModalVisible(true)}>+ 添加</Button>
        <Input.Search
          placeholder="搜索"
          style={{ width: 200 }}
          allowClear
          value={searchValue}
          onChange={e => setSearchValue(e.target.value)}
          onSearch={handleSearch}
        />
        <Button
          style={{ marginLeft: 8 }}
          onClick={() => {
            setSearchValue('');
            getList();
          }}
        >
          重置
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={list}
        bordered
        size="middle"
        loading={loading}
        rowClassName={(record, index) => index % 2 === 1 ? 'ant-table-row-striped' : ''}
        pagination={{
          showTotal: (total) => `共 ${total} 条记录`,
          showQuickJumper: true,
        }}
        rowKey="_id"
      />

      {/* 添加会议纪要模态框 */}
      <Modal
        title={editingId ? "编辑会议纪要" : "添加会议纪要"}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingId(null);
        }}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleFinish}
        >
          <Form.Item label="会议时间" required>
            <Space>
              <Form.Item name="startTime" noStyle rules={[{ required: true, message: '请选择开始时间' }]}>
                <DatePicker showTime format="YYYY-MM-DD HH:mm" />
              </Form.Item>
              <span>-</span>
              <Form.Item name="endTime" noStyle rules={[{ required: true, message: '请选择结束时间' }]}>
                <DatePicker showTime format="YYYY-MM-DD HH:mm" />
              </Form.Item>
            </Space>
          </Form.Item>
          <Form.Item label="会议主题" name="MeetingName" rules={[{ required: true, message: '请输入会议主题' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="参会人" name="Participants" rules={[{ required: true, message: '请输入参会人' }]}>
            <Input.TextArea rows={2} />
          </Form.Item>
          <Form.Item
            label="会议事项记录"
            name="cahier"
            valuePropName="fileList"
            getValueFromEvent={e => Array.isArray(e) ? e : e && e.fileList}
            rules={[{ required: true, message: '请上传会议事项记录文件' }]}
          >
            <Upload
              beforeUpload={() => false}
              maxCount={1}
              listType="text"
              accept=".doc,.docx,.xls,.xlsx,image/*,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            >
              <Button icon={<UploadOutlined />}>上传事项记录文件</Button>
            </Upload>
          </Form.Item>
          <Form.Item label="创建人" name="creator" rules={[{ required: true, message: '请输入创建人' }]}>
            <Input />
          </Form.Item>
          <Form.Item
            label="会议附件"
            name="file"
            valuePropName="fileList"
            getValueFromEvent={e => Array.isArray(e) ? e : e && e.fileList}
          >
            <Upload
              beforeUpload={() => false}
              maxCount={1}
              listType="picture"
              accept=".doc,.docx,.xls,.xlsx,image/*,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            >
              <Button icon={<UploadOutlined />}>选择文件</Button>
            </Upload>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">保存</Button>
              <Button onClick={() => setModalVisible(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 文档预览模态框 */}
      {currentFile && (
        <div >
          <DocumentPreview
            visible={previewVisible}
            fileUrl={currentFile.url}
            fileName={currentFile.name}
            onClose={() => {
              setPreviewVisible(false);
              setCurrentFile(null);
            }}
            onEdit={(fileUrl, fileName,) => {
              setPreviewVisible(false);
              const record = list.find(item => item.url === fileUrl && item.name === fileName);
              if (record) {
                // ...回填表单...
                setEditingId(record._id);
              }
              setModalVisible(true);
            }}
          />
        </div>
      )}
    </div>
  );
} 